<template>
  <div class="batch-list-container">
    <div class="page-header">
      <h1>茶叶批次管理</h1>
      <el-button 
        type="primary" 
        @click="goToCreate"
        v-if="canCreate"
      >
        <el-icon><Plus /></el-icon>
        创建批次
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filters" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="filters.keyword"
            placeholder="批次ID、名称或品种"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="选择状态" clearable>
            <el-option label="已创建" value="created" />
            <el-option label="生产中" value="production" />
            <el-option label="运输中" value="logistics" />
            <el-option label="销售中" value="sales" />
            <el-option label="已消费" value="consumed" />
          </el-select>
        </el-form-item>
        <el-form-item label="品种">
          <el-input v-model="filters.variety" placeholder="茶叶品种" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 批次列表 -->
    <el-card class="list-card">
      <div v-loading="loading">
        <el-table
          :data="batches"
          stripe
          @row-click="handleRowClick"
          style="cursor: pointer;"
        >
          <el-table-column prop="batchId" label="批次ID" min-width="150">
            <template #default="{ row }">
              <el-text class="batch-id">{{ row.batchId }}</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="茶叶名称" min-width="120" />
          <el-table-column prop="variety" label="品种" width="100" />
          <el-table-column prop="grade" label="等级" width="80" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                text
                @click.stop="viewDetail(row._id)"
              >
                查看
              </el-button>
              <el-button
                type="warning"
                text
                @click.stop="editBatch(row._id)"
                v-if="canEdit(row)"
              >
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.limit"
            :page-sizes="[10, 20, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { apiMethods } from '@/api'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 状态
const loading = ref(false)
const batches = ref([])
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
})

const filters = reactive({
  keyword: '',
  status: '',
  variety: ''
})

// 计算属性
const user = computed(() => authStore.user)

const canCreate = computed(() => {
  return ['farmer', 'admin'].includes(user.value?.role)
})

const canEdit = (batch) => {
  if (user.value?.role === 'admin') return true
  if (user.value?.role === 'farmer' && batch.createdBy === user.value._id) return true
  return false
}

// 方法
const loadBatches = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      ...filters
    }

    // 清理空值
    Object.keys(params).forEach(key => {
      if (params[key] === '') delete params[key]
    })

    const response = await apiMethods.batches.getList(params)
    
    if (response.data.success) {
      batches.value = response.data.data.list
      pagination.total = response.data.data.pagination.total
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    console.error('加载批次列表失败:', error)
    ElMessage.error('加载批次列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadBatches()
}

const resetFilters = () => {
  filters.keyword = ''
  filters.status = ''
  filters.variety = ''
  handleSearch()
}

const handleSizeChange = (size) => {
  pagination.limit = size
  pagination.page = 1
  loadBatches()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadBatches()
}

const handleRowClick = (row) => {
  viewDetail(row._id)
}

const viewDetail = (batchId) => {
  router.push(`/batches/${batchId}`)
}

const editBatch = (batchId) => {
  router.push(`/batches/${batchId}/edit`)
}

const goToCreate = () => {
  router.push('/batches/create')
}

const getStatusLabel = (status) => {
  const statusMap = {
    created: '已创建',
    production: '生产中',
    logistics: '运输中',
    sales: '销售中',
    consumed: '已消费'
  }
  return statusMap[status] || status
}

const getStatusType = (status) => {
  const typeMap = {
    created: 'info',
    production: 'warning',
    logistics: 'primary',
    sales: 'success',
    consumed: 'info'
  }
  return typeMap[status] || 'info'
}

const formatTime = (timeStr) => {
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 初始化
onMounted(() => {
  loadBatches()
})
</script>

<style scoped>
.batch-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #2c3e50;
}

.filter-card {
  margin-bottom: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.batch-id {
  font-family: monospace;
  font-size: 12px;
  color: #409eff;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式 */
@media (max-width: 768px) {
  .batch-list-container {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filter-card :deep(.el-form) {
    flex-direction: column;
  }
  
  .filter-card :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 16px;
  }
}
</style>